﻿using System;
using System.Collections.Generic;
using System.Web;

namespace RG.Common.Provider
{
    internal interface ISessionStorage
    {
        IDAOSession DAOSession { get; set; }
    }

    internal class HttpSessionStorage : ISessionStorage
    {
        private readonly String providerName;

        public HttpSessionStorage(string providerName)
        {
            this.providerName = providerName;
        }

        public IDAOSession DAOSession
        {
            get { return (IDAOSession)HttpContext.Current.Items[providerName]; }
            set { HttpContext.Current.Items[providerName] = value; }
        }
    }

    internal class ThreadSessionStorage : ISessionStorage
    {
        [ThreadStatic] 
        private static Dictionary<string, IDAOSession> sessionContainer;

        private static Dictionary<string, IDAOSession> daoSessions
        {
            get
            {
                if (sessionContainer == null)
                    sessionContainer = new Dictionary<string, IDAOSession>();

                return sessionContainer;
            }
        }

        private readonly String providerName;

        public ThreadSessionStorage(string providerName)
        {
            this.providerName = providerName;
        }

        public IDAOSession DAOSession
        {
            get { return daoSessions.ContainsKey(providerName) ? daoSessions[providerName] : null; }
            set { daoSessions[providerName] = value; }
        }
    }

    internal static class SessionStorageFactory
    {
        public static ISessionStorage GetSessionStorage(string providerName)
        {
            if (HttpContext.Current == null)
                return new ThreadSessionStorage(providerName);

            return new HttpSessionStorage(providerName);
        }
    }
}